package com.wms.security.filter;

import com.wms.plugin.JwtPlugin;
import com.wms.security.MyAuthenticationFailureHandler;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component("openFilter")
public class OpenFilter extends UrlFilter {

    @Autowired
    private JwtPlugin jwtPlugin;

    @Autowired
    private MyAuthenticationFailureHandler failureHandler;

    @Override
    public void filter(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String servletPath = request.getServletPath();
        if (servletPath.startsWith("/open")) {
            if (servletPath.equals("/open/resource/menu")){
                Claims claims = getClaims(request, jwtPlugin);
                if (claims == null) {
                    failureHandler.onAuthenticationFailure(request, response, null);
                    throw new CredentialsExpiredException("登录失效");
                }

                request.setAttribute("username", claims.getId());
            }
        }
    }
}
